package com.taotao.item.listener;

import com.taotao.item.pojo.Item;
import com.taotao.manager.pojo.TbItem;
import com.taotao.manager.pojo.TbItemDesc;
import com.taotao.manager.service.ItemDescService;
import com.taotao.manager.service.ItemService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

public class ItemChangeMessageListener implements MessageListener {
    @Autowired
    private ItemService itemService;
    @Autowired
    private ItemDescService itemDescService;
    @Autowired
    private FreeMarkerConfigurer configurer;
    /**
     * 监听到item-change-topic的消息之后,生成freemarker静态页面
     */
    @Override
    public void onMessage(Message message) {
        if (message instanceof TextMessage) {
            TextMessage message1= (TextMessage) message;
            try {
                long itemId = Long.parseLong(message1.getText());
                TbItem tbItem = itemService.getItemById(itemId);
                Item item = new Item(tbItem);
                TbItemDesc itemDesc = itemDescService.getItemDesc(itemId);
                genHtmlFreemarker(item, itemDesc);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void genHtmlFreemarker(Item item, TbItemDesc itemDesc) throws Exception{
        Configuration configuration = configurer.getConfiguration();
        Template template = configuration.getTemplate("item.ftl");
        @SuppressWarnings("unchecked")
        Map model = new HashMap();
        model.put("item",item);
        model.put("itemDesc", itemDesc);

        Writer writer = new FileWriter("i:/freemarker/item/" + item.getId() + ".html");
        template.process(model,writer);
        writer.close();
    }
}
